package cn.edu.sdjzu.util;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "Auth", urlPatterns = "/*")
public class JwtAuthFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化过滤器
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 获取请求路径
        String path = request.getRequestURI();
        System.out.println("path=" + path);

        // 如果无须验证，直接放行
        String loginUrl = ConfigUtil.getProperty("login.url");
        if (path.endsWith(loginUrl) || path.endsWith("/bysj/")) {
            filterChain.doFilter(request, response);
            return;
        }

        // 从请求头中的Authorization字段获取Token
        String authorizationHeader = request.getHeader("Authorization");
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 验证失败，返回未授权状态码
        } else {
            String token = authorizationHeader.substring(7).trim(); // 移除前缀"Bearer"和空格

            // 验证Token
            if (JwtUtil.validateToken(token)) {
                filterChain.doFilter(request, response); // 验证通过，继续处理请求
            } else {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 验证失败，返回未授权状态码
            }
        }
    }

    @Override
    public void destroy() {
        // 销毁过滤器
    }
}